/**
 * v-copy
 * 复制某个值至剪贴板
 * 接收参数：string类型/Ref<string>类型/Reactive<string>类型
 */
import type { Directive, DirectiveBinding } from "vue";
import { ElMessage } from "element-plus";
interface ElType extends HTMLElement {
  copyData: string | number;
  __handleClick__: any;
}
const copy: Directive = {
  mounted(el: ElType, binding: DirectiveBinding) {
    el.copyData = binding.value;
    el.addEventListener("click", handleClick);
  },
  updated(el: ElType, binding: DirectiveBinding) {
    el.copyData = binding.value;
  },
  beforeUnmount(el: ElType) {
    el.removeEventListener("click", el.__handleClick__);
  }
};

async function handleClick(this: any) {
  try {
    // 尝试使用 Clipboard API 进行复制
    await navigator.clipboard.writeText(this.copyData);
    ElMessage({
      type: "success",
      message: "复制成功"
    });
  } catch (err) {
    console.error("Clipboard API 复制失败，尝试使用备用方法: ", err);

    // 如果 Clipboard API 不支持或出错，使用 textarea 方法进行复制
    let textArea = document.createElement("textarea");
    textArea.value = this.copyData;

    // 隐藏 textarea，使其不影响页面布局
    textArea.style.position = "absolute";
    textArea.style.opacity = "0";
    textArea.style.left = "-999999px";
    textArea.style.top = "-999999px";

    document.body.appendChild(textArea);
    textArea.focus();
    textArea.select();

    try {
      // 使用 document.execCommand('copy') 执行复制
      if (document.execCommand("copy")) {
        ElMessage({
          type: "success",
          message: "复制成功"
        });
      } else {
        throw new Error("execCommand 复制失败");
      }
    } catch (execErr) {
      console.error("复制操作不被支持或失败: ", execErr);
      ElMessage({
        type: "error",
        message: "复制失败，请手动复制"
      });
    } finally {
      // 移除 textarea 元素
      document.body.removeChild(textArea);
    }
  }
}

export default copy;
